package com.dc.di.sf.dt;

import org.apache.axiom.om.OMElement;

import com.dc.di.sf.utils.DataTypeUtils;
import com.dc.di.sf.utils.OMUtils;

public class UnitData implements DTObject<UnitData> {

	public static final String TAG_UNITDATA = "UnitData";
	public static final String TAG_UNITIDNAME = "UnitIDName";
	public static final String TAG_UNITDISPLAYNAME = "UnitDisplayName";
	public static final String TAG_UNITVALUE = "UnitValue";

	private DataUnit dataUnit;
	private Object unitValue;

	public UnitData(DataUnit dataUnit) {
		this.dataUnit = dataUnit;
	}

	public String getUnitIdName() {
		return dataUnit.getIdName();
	}

	public String getUnitDisplayName() {
		return dataUnit.getDisplayName();
	}

	/**
	 * @return the unitValue
	 */
	public Object getUnitValue() {
		return unitValue;
	}

	/**
	 * @param unitValue
	 *            the unitValue to set
	 */
	public void setUnitValue(Object unitValue) {
		this.unitValue = unitValue;
	}

	public OMElement toXML() {
		OMElement data = OMUtils.createOMElement(TAG_UNITDATA);
		data.addChild(OMUtils.createOMElementWithText(TAG_UNITIDNAME, dataUnit.getIdName()));
		data.addChild(OMUtils.createOMElementWithText(TAG_UNITDISPLAYNAME, dataUnit.getDisplayName()));
		data.addChild(OMUtils.createOMElementWithText(TAG_UNITVALUE, DataTypeUtils.value2Text(unitValue)));
		return data;
	}

	public UnitData fromXML(OMElement xml) {
		if (xml != null)
			if (dataUnit == null) {
				dataUnit = new DataUnit();
				dataUnit.setIdName(OMUtils.getTextOfChild(xml, TAG_UNITIDNAME));
				dataUnit.setDisplayName(OMUtils.getTextOfChild(xml, TAG_UNITDISPLAYNAME));
				unitValue = OMUtils.getTextOfChild(xml, TAG_UNITVALUE);
			} else {
				unitValue = DataTypeUtils
						.text2Value(OMUtils.getTextOfChild(xml, TAG_UNITVALUE), dataUnit.getDataType());
			}
		return this;
	}

	/* (non-Javadoc)
	 * @see com.dc.di.sf.dt.DTObject#toXMLString()
	 */
	public String toXMLString() {
		StringBuilder sb = new StringBuilder();
		sb.append(OMUtils.generateOMElementBeginString(TAG_UNITDATA));
		sb.append(OMUtils.generateOMElementString(TAG_UNITIDNAME, dataUnit.getIdName()));
		sb.append(OMUtils.generateOMElementString(TAG_UNITDISPLAYNAME, dataUnit.getDisplayName()));
		sb.append(OMUtils.generateOMElementString(TAG_UNITVALUE, DataTypeUtils.value2Text(unitValue)));
		sb.append(OMUtils.generateOMElementEndString(TAG_UNITDATA));
		return sb.toString();
	}

}
